import IntegrationTable, {
	IntegrationTableProps,
} from "@/components/IntegrationTable";
import type { ProColumns, ActionType } from "@ant-design/pro-table";
import React, { useEffect, useRef, useState } from "react";
import { Image, Radio, Select, message, Card, Tabs } from "antd";
import { DynamicFormItem } from "@/components/DynamicForm";
import { areaList, userList } from "./service";
import { arrayToObject, getArray, getString, getObject } from "phinney-toolkit";
import axios from "axios";
// @page 商家
const Business: React.FC<any> = () => {
	// 组件是否已经卸载
	let isUnMounted = false;
	let actionref: any = useRef();
	let [area, setArea] = useState<any>([]);
	let [user, setUserList] = useState<any>([]);
	const [realDateStatus, setrealDateStatus] = useState<any>("0");
	const statusType = [
		{ label: "正常", value: 1 },
		{ label: "禁用", value: 2 },
	];
	const postsType = [
		{ label: "普通帖子", value: "30" },
		{ label: "闲置帖子", value: "40" },
	];

	const getAreaList = async () => {
		const res = await areaList({
			cityCode: "410100",
			pageIndex: "1",
			pageSize: "99",
		});
		!isUnMounted &&
			setArea(
				getArray(res?.data.records).map((item) => ({
					label: item?.areaName,
					value: item?.areaCode,
				}))
			);
	};

	const getUserList = async () => {
		const res = await userList({
			pageIndex: "1",
			pageSize: "200",
			realDateStatus: 0,
		});
		!isUnMounted &&
			setUserList(
				getArray(res?.data.records).map((item) => ({
					label: item?.userNickName,
					value: item?.userCode,
				}))
			);
	};
	// 表格项
	const columns: ProColumns[] = [
		{
			title: "昵称",
			dataIndex: "nickName",
			search: false,
		},
		{
			title: "帖子分类",
			dataIndex: "categoryValue",
			search: false,
			valueEnum: {
				"10": "母婴",
				"20": "亲子",
				"30": "断舍离",
				"40": "萌宠",
			},
		},
		{
			title: "帖子标题",
			dataIndex: "title",
			search: false,
			width: 200,
		},
		{
			title: "帖子内容",
			dataIndex: "content",
			search: false,
			width: 200,
		},
		{
			title: "帖子图片",
			dataIndex: "picUrl",
			search: false,
			width: 320,
			render: (_, record: any) => {
				return (
					<Image.PreviewGroup>
						{record.picUrl.map((item: any) => {
							return <Image src={item} width={50} alt="" />;
						})}
					</Image.PreviewGroup>
				);
			},
		},
		{
			title: "状态",
			dataIndex: "status",
			search: false,
			valueEnum: {
				1: "正常",
				2: "禁用",
			},
		},
		{
			title: "分类模块",
			dataIndex: "categoryValue",
			hideInTable: true,
			valueEnum: {
				"10": "母婴",
				"20": "亲子",
				"30": "断舍离",
				"40": "萌宠",
			},
		},
		{
			title: "创建日期",
			dataIndex: "createTime",
			search: false,
		},
		{
			title: "更新日期",
			dataIndex: "updateTime",
			search: false,
		},
	];

	const getFormItemsSend2 = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		return [
			{
				type: "select",
				label: "发布人",
				name: "userCode",
				options: user,
				required: true,
			},
			{
				type: "custom",
				label: "发布帖子类型",
				name: "articleType",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={postsType}
							defaultValue={record?.articleType}
							onChange={({ target }) => {
								form?.setFieldsValue({ articleType: target?.value });
								vm.setState({
									isTrue: target.value == "40",
								});
							}}
						></Radio.Group>
					);
				},
			},

			{
				type: "upload",
				label: "商品图片",
				name: "picList",
				fieldProps: {
					limit: 6,
				},
				required: true,
			},
			{
				type: "text",
				label: "标题",
				name: "title",
				required: true,
			},
			{
				type: "text",
				label: "点赞数",
				name: "likesNum",
			},
			{
				type: "textarea",
				label: "内容",
				name: "content",
				required: true,
			},
			{
				type: "select",
				label: "话题",
				name: "categoryValue",
				required: true,
				options: [
					{
						label: "母婴",
						value: "10",
					},
					{
						label: "亲子",
						value: "20",
					},
					{
						label: "断舍离",
						value: "30",
					},
					{
						label: "萌宠",
						value: "40",
					},
				],
			},
			{
				type: "select",
				label: "区域",
				name: "areaCode",
				options: area,
				required: false,
			},
			{
				type: "custom",
				label: "小区名称",
				name: "communityName",
				required: false,
				render: (form: any, formValues: any) => {
					return (
						<div style={{ width: "100%" }}>
							<Select
								id="Community"
								showSearch
								placeholder="请输入小区名称"
								showArrow={false}
								filterOption={false}
								defaultValue={formValues.communityName || ""}
								optionLabelProp="label"
								onSearch={(value: any) => {
									let isAreaCode = form.getFieldValue("areaCode");
									if (!isAreaCode) {
										message.error("请选择区域!");
										return false;
									} else {
										axios
											.get(
												`https://restapi.amap.com/v3/place/text?key=10c01e3af3272d167f7ab9880eb137c5&types=120000&keywords=${value}&city=${isAreaCode}&extensions=all`
											)
											.then((response) => {
												let result = response.data.pois;
												vm.setState({
													community: result,
												});
											});
									}
								}}
								onChange={(value: any, option: any) => {
									console.log(option, value, option.adname);
									let address = "";
									if (option.business_area) {
										address = `河南省郑州市${option.adname}${option.business_area}${option.address}`;
									} else {
										address = `河南省郑州市${option.adname}${option.address}`;
									}
									let location = option.location.split(",");
									form.setFieldsValue({
										communityCode: option.key,
										address,
										lon: location[0],
										lat: location[1],
										communityName: `${option.value},${option.key},${address},`,
									});
								}}
							>
								{getArray(vm.state.community).map((item: any) => {
									return (
										<Select.Option
											key={item.id}
											value={item.name}
											location={item.location}
											address={item.address}
											adname={item.adname}
											business_area={item.business_area}
										>
											{item.name}
										</Select.Option>
									);
								})}
							</Select>
						</div>
					);
				},
			},
			{
				type: "text",
				label: "小区code",
				name: "communityCode",
				required: false,
			},
			{
				type: "text",
				label: "小区详细地址",
				name: "address",
				required: false,
			},
			...(vm.state.isTrue
				? [
						{
							type: "text",
							label: "价格",
							name: "price",
							required: true,
						},
				  ]
				: []),
		];
	};

	const getFormItems = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "custom",
				label: "状态",
				name: "status",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={statusType}
							defaultValue={record?.status}
							onChange={({ target }) => {
								form?.setFieldsValue({ status: target?.value });

								vm.setState({
									isTrue: target.value == "2",
								});
							}}
						></Radio.Group>
					);
				},
			},

			...(vm.state.isTrue
				? [
						{
							type: "textarea",
							label: "拒绝理由",
							name: "rejectReason",
							required: true,
						},
				  ]
				: []),
		];
	};

	// 一体化表格props
	const tablePorps: IntegrationTableProps = {
		rowKey: "articleId",
		scroll: { x: 1000 },
		columns,
		ref: (refs: any) => {
			actionref = refs?.actionRef;
		},
		listProps: {
			url: "/article/authList",
			method: "GET",
			requestType: "params",
			paramsHandle: (params: any) => {
				return {
					...params,
					realDateStatus,
				};
			},
		},
		addProps: {
			url: "/article/publish",
			method: "POST",
			requestType: "params",
			formValuesHandle: (record: any) => {
				return {
					...record,
				};
			},
			paramsHandle: (params: any, form: any) => {
				params.communityName = params.communityName.split(",");
				params.picList = (
					params?.picList?.map((item: any) => item.url) || []
				).join(",");
				return {
					...params,
					address_flag: 1,
					addressStatus: 1,
					communityName: params.communityName[0],
					communityCode: params.communityName[1],
					address: params.communityName[2] ? params.communityName[2] : "",
					lon: 0,
					lat: 0,
				};
			},
			modalProps: {
				title: "发布帖子",
				formProps: {
					labelCol: { span: 8 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItemsSend2(vm);
				},
			},
		},
		handleOperating: (items: any[]) => [
			{
				type: "modal",
				props: {
					url: "/article/updateArticleStatus",
					method: "POST",
					btnText: "审核",
					modalProps: {
						formProps: {
							labelCol: { span: 8 },
						},
						title: "审核帖子",
						formItems: [
							{
								type: "custom",
								label: "状态",
								name: "status",
								required: true,
								render: (form: any, record: any) => {
									return (
										<Radio.Group
											options={statusType}
											onChange={({ target }) => {
												form?.setFieldsValue({ status: target?.value });
												// items[0].formValue = target?.value;
												// console.log(items);
											}}
										></Radio.Group>
									);
								},
							},
							{
								type: "textarea",
								label: "禁用理由",
								name: "rejectReason",
							},
						],
					},
				},
			},
			{
				type: "modal",
				props: {
					url: "/article/update",
					method: "POST",
					btnText: "编辑",
					modalProps: {
						formValuesHandle: async (record: any, form: any) => {
							const { ...others } = record;
							return {
								...others,
								picList: !!record.picUrl
									? [
											...record.picUrl.map((item: any, index: any) => {
												return {
													uid: index,
													status: "done",
													name: item,
													url: item,
												};
											}),
									  ]
									: [],
							};
						},
						formProps: {
							labelCol: { span: 8 },
						},
						title: "编辑帖子",
						formItems: [
							{
								type: "select",
								label: "发布人",
								name: "userCode",
								options: user,
								required: true,
							},
							// {
							// 	type: "custom",
							// 	label: "发布帖子类型",
							// 	name: "articleType",
							// 	required: true,
							// 	render: (form: any, record: any) => {
							// 		return (
							// 			<Radio.Group
							// 				options={postsType}
							// 				defaultValue={record?.articleType}
							// 				onChange={({ target }) => {
							// 					form?.setFieldsValue({ articleType: target?.value });
							// 					console.log(items, "->>>>>>items");
							// 				}}
							// 			></Radio.Group>
							// 		);
							// 	},
							// },
							{
								type: "upload",
								label: "商品图片",
								name: "picList",
								fieldProps: {
									limit: 6,
								},
								required: true,
							},
							{
								type: "text",
								label: "标题",
								name: "title",
								required: true,
							},
							{
								type: "text",
								label: "点赞数",
								name: "likesNum",
							},
							{
								type: "textarea",
								label: "内容",
								name: "content",
								required: true,
							},
							{
								type: "select",
								label: "话题",
								name: "categoryValue",
								required: true,
								options: [
									{
										label: "母婴",
										value: 10,
									},
									{
										label: "亲子",
										value: 20,
									},
									{
										label: "断舍离",
										value: 30,
									},
									{
										label: "萌宠",
										value: 40,
									},
								],
							},
							// {
							// 	type: "text",
							// 	label: "价格",
							// 	name: "price",
							// },
							// ...(vm.state.isTrue
							// 	? [
							// 			{
							// 				type: "text",
							// 				label: "价格",
							// 				name: "price",
							// 				required: true,
							// 			},
							// 	  ]
							// 	: []),
						],
					},
					paramsHandle: ({ ...params }: any, record: any) => {
						params.picUrl = (
							params?.picList?.map((item: any) => item.url) || []
						).join(",");
						params.picList = (
							params?.picList?.map((item: any) => item.url) || []
						).join(",");
						return {
							...params,
						};
					},
				},
			},
		],
		tableBefore: () => {
			return (
				<div>
					<Card>
						<Tabs
							onChange={(activeKey) => {
								setrealDateStatus(activeKey);
								actionref?.reload();
							}}
						>
							<Tabs.TabPane tab={"测试用户"} key="0"></Tabs.TabPane>
							<Tabs.TabPane tab={"普通用户"} key="1"></Tabs.TabPane>
						</Tabs>
					</Card>
				</div>
			);
		},
	};

	// 初始化加载数据
	useEffect(() => {
		getAreaList();
		getUserList();
		return () => {
			isUnMounted = true;
		};
	}, []);

	return <IntegrationTable {...tablePorps} />;
};

export default Business;
